package db4oClass.server;

import general.dbClass.DBCategory;
import general.dbClass.DBExif;
import general.dbClass.DBKeyword;
import general.dbClass.DBPicInfo;

import com.db4o.*;
import com.db4o.cs.*;
import com.db4o.cs.config.*;
import com.db4o.messaging.*;

import db4oClass.ServerInfo;

public class MyServer implements ServerInfo,MessageRecipient {
	private boolean stop = false;
	
	public static void main(String[] args) {
		new MyServer().runServer();
	}

	private void runServer() {
		synchronized (this) {
			ServerConfiguration config = Db4oClientServer.newServerConfiguration();
			
			config.common().objectClass(DBPicInfo.class).objectField("nr").indexed(true);
			config.common().objectClass(DBCategory.class).objectField("nr").indexed(true);
			config.common().objectClass(DBKeyword.class).objectField("nr").indexed(true);	
			config.common().objectClass(DBPicInfo.class).cascadeOnUpdate(true);
			config.common().objectClass(DBCategory.class).cascadeOnUpdate(true);
			config.common().objectClass(DBKeyword.class).cascadeOnUpdate(true);
			
			config.common().objectClass(DBCategory.class).cascadeOnDelete(true);
			config.common().objectClass(DBKeyword.class).cascadeOnDelete(true);
			//config.common().objectClass(DBPicInfo.class).cascadeOnDelete(true);
			config.common().objectClass(DBExif.class);
			
			config.networking().messageRecipient(this);
			
			ObjectServer db4oServer = Db4oClientServer.openServer(config,
																  FILE,
																  PORT);
			db4oServer.grantAccess(USER, PASS);
			
			Thread.currentThread().setName(this.getClass().getName());
			System.out.println("Db4o Server is now running on host: " + HOST + " port: " + PORT);
			
			try {
				if(!stop) {
					this.wait(Long.MAX_VALUE);
				}
			}catch(Exception e) {
				System.err.println(e);
				System.out.println("Server close because of error");
				db4oServer.close();
			}
			
			System.out.println("Server close because of time out.");
			db4oServer.close();
		}
	}
	

	public void processMessage(MessageContext con, Object message) {
		if(message instanceof StopServer) {
			close();
		}
	}
	
	public void close() {
		synchronized(this) {
			stop = true;
			this.notify();
		}
	}
}
